package com.chinasofti.thread07;


import java.util.concurrent.locks.ReentrantLock;

public class SellTicket implements Runnable {
    private int ticketsCount = 100;
    private Object obj = new Object();
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
//         synchronized (obj) {
            //进入循环直接上锁
            try {
                lock.lock();
                if (ticketsCount == 0) {
                    break;
                } else {
                    Thread.sleep(100);//t1休息了100毫秒
                    //卖票1张
                    ticketsCount--;
                    System.out.println(Thread.currentThread().getName() + "在卖票，还剩下" + ticketsCount + "张票");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();//释放锁
            }
        }
    }
}

class SellTicketDemo{
    public static void main(String[] args) {
       SellTicket st = new SellTicket();
        Thread t1 = new Thread(st,"窗口1");
        Thread t2 = new Thread(st,"窗口2");
        t1.start();
        t2.start();
    }
}